﻿using System;
using System.Linq;
using System.Text;

namespace ConcurrantLoadingLib
{
    public class Trade
    {
        public readonly string OrderId;
        public readonly string Ticker;
        public readonly int Quantity;
        
        private double _price;
        private readonly object _priceLock = new object();

        public event EventHandler<PriceChangedEventArgs> PriceChanged;
        
        public Trade(string orderId, string ticker, int quantity, double price)
        {
            OrderId = orderId;
            Ticker = ticker;
            Quantity = quantity;
            Price = price;

            PriceTicker.Instance.PriceChanged += PriceTickerPriceChanged;
        }

        private void PriceTickerPriceChanged(object sender, PriceChangedEventArgs e)
        {
            Price = Price + e.Change;
            if (PriceChanged != null)
                PriceChanged(this, e); // replace sender with this trade object
        }

        public double Price
        {
            get 
            { 
                lock(_priceLock)
                    return _price; 
            }
            set
            {
                lock (_priceLock) 
                    _price = value;
            }
        }

        public double Notional
        {
            get
            {
                return Quantity * Price;
            }
        }

        public override string ToString()
        {
            return string.Format("OrderId={0} Ticker={1} Quantity={2} Price={3} Notional={4}", OrderId, Ticker, Quantity, Price, Notional);
        }
    }
}